#include "stdafx.h"
#include "net/WebSocketImpl.hpp"
#include "net/WebSocket.hpp"
#include "stream/streambuf.hpp"
#include "stream/buffer.hpp"
using namespace JHCPP::stream;
#include "utils/format.hpp"
using JHCPP::utils::format;

NET_NAMESPACE_BEGIN

int CWebSocketImpl::frameFlags() const
{
	return m_frameFlags;
}

bool CWebSocketImpl::mustMaskPayload() const
{
	return m_mustMaskPayload;
}

CWebSocketImpl::CWebSocketImpl(CStreamSocketImpl* pStreamSocketImpl, bool mustMaskPayload)
	: CStreamSocketImpl(pStreamSocketImpl->sockfd()),
	m_pStreamSocketImpl(pStreamSocketImpl),
	m_frameFlags(0),
	m_mustMaskPayload(mustMaskPayload)
{
	jh_check_ptr(pStreamSocketImpl);
	m_pStreamSocketImpl->add();
}

CWebSocketImpl::~CWebSocketImpl()
{
	try
	{
		m_pStreamSocketImpl->release();
		reset();
	}
	catch (...)
	{
		jh_unexpected();
	}
}

int CWebSocketImpl::sendBytes(const void* buffer, int length, int flags)
{
	TBuffer<char> frame(length + MAX_HEADER_LENGTH);
	CMemoryOutputStream ostr(frame.begin(), frame.size());
	CBinaryWriter writer(ostr, CBinaryWriter::NETWORK_BYTE_ORDER);

	if (flags == 0) flags = CWebSocket::FRAME_BINARY;
	flags &= 0xff;
	writer << static_cast<UInt8>(flags);
	UInt8 lengthByte(0);
	if (m_mustMaskPayload)
	{
		lengthByte |= FRAME_FLAG_MASK;
	}
	if (length < 126)
	{
		lengthByte |= static_cast<UInt8>(length);
		writer << lengthByte;
	}
	else if (length < 65536)
	{
		lengthByte |= 126;
		writer << lengthByte << static_cast<UInt16>(length);
	}
	else
	{
		lengthByte |= 127;
		writer << lengthByte << static_cast<UInt64>(length);
	}
	if (m_mustMaskPayload)
	{
		const UInt32 mask = m_rnd.next();
		const char* m = reinterpret_cast<const char*>(&mask);
		const char* b = reinterpret_cast<const char*>(buffer);
		writer.writeRaw(m, 4);
		char* p = frame.begin() + ostr.charsWritten();
		for (int i = 0; i < length; i++)
		{
			p[i] = b[i] ^ m[i % 4];
		}
	}
	else
	{
		std::memcpy(frame.begin() + ostr.charsWritten(), buffer, length);
	}
	m_pStreamSocketImpl->sendBytes(frame.begin(), length + static_cast<int>(ostr.charsWritten()));
	return length;
}

int CWebSocketImpl::receiveBytes(void* buffer, int length, int)
{
	char header[MAX_HEADER_LENGTH];
	int n = receiveNBytes(header, 2);
	if (n <= 0)
	{
		m_frameFlags = 0;
		return n;
	}
	jh_assert (n == 2);
	UInt8 lengthByte = static_cast<UInt8>(header[1]);
	int maskOffset = 0;
	if (lengthByte & FRAME_FLAG_MASK) maskOffset += 4;
	lengthByte &= 0x7f;
	if (lengthByte > 0 || maskOffset > 0)
	{
		if (lengthByte + 2 + maskOffset < MAX_HEADER_LENGTH)
		{
			n = receiveNBytes(header + 2, lengthByte + maskOffset);
		}
		else
		{
			n = receiveNBytes(header + 2, MAX_HEADER_LENGTH - 2);
		}
		if (n <= 0) throw WebSocketException("Incomplete header received", CWebSocket::WS_ERR_INCOMPLETE_FRAME);
		n += 2;
	}
	CMemoryInputStream istr(header, n);
	CBinaryReader reader(istr, CBinaryReader::NETWORK_BYTE_ORDER);
	UInt8 flags;
	char mask[4];
	reader >> flags >> lengthByte;
	m_frameFlags = flags;
	int payloadLength = 0;
	int payloadOffset = 2;
	if ((lengthByte & 0x7f) == 127)
	{
		UInt64 l;
		reader >> l;
		if (l > length) throw WebSocketException(format("Insufficient buffer for payload size %Lu", l), CWebSocket::WS_ERR_PAYLOAD_TOO_BIG);
		payloadLength = static_cast<int>(l);
		payloadOffset += 8;
	}
	else if ((lengthByte & 0x7f) == 126)
	{
		UInt16 l;
		reader >> l;
		if (l > length) throw WebSocketException(format("Insufficient buffer for payload size %hu", l), CWebSocket::WS_ERR_PAYLOAD_TOO_BIG);
		payloadLength = static_cast<int>(l);
		payloadOffset += 2;
	}
	else
	{
		UInt8 l = lengthByte & 0x7f;
		if (l > length) throw WebSocketException(format("Insufficient buffer for payload size %u", unsigned(l)), CWebSocket::WS_ERR_PAYLOAD_TOO_BIG);
		payloadLength = static_cast<int>(l);
	}
	if (lengthByte & FRAME_FLAG_MASK)
	{
		reader.readRaw(mask, 4);
		payloadOffset += 4;
	}
	int received = 0;
	if (payloadOffset < n)
	{
		std::memcpy(buffer, header + payloadOffset, n - payloadOffset);
		received = n - payloadOffset;
	}
	if (received < payloadLength)
	{
		n = receiveNBytes(reinterpret_cast<char*>(buffer) + received, payloadLength - received);
		if (n <= 0) throw WebSocketException("Incomplete frame received", CWebSocket::WS_ERR_INCOMPLETE_FRAME);
		received += n;
	}
	if (lengthByte & FRAME_FLAG_MASK)
	{
		char* p = reinterpret_cast<char*>(buffer);
		for (int i = 0; i < received; i++)
		{
			p[i] ^= mask[i % 4];
		}
	}
	return received;
}

int CWebSocketImpl::receiveNBytes(void* buffer, int bytes)
{
	int received = m_pStreamSocketImpl->receiveBytes(reinterpret_cast<char*>(buffer), bytes);
	if (received > 0)
	{
		while (received < bytes)
		{
			int n = m_pStreamSocketImpl->receiveBytes(reinterpret_cast<char*>(buffer) + received, bytes - received);
			if (n > 0)
				received += n;
			else
				throw WebSocketException("Incomplete frame received", CWebSocket::WS_ERR_INCOMPLETE_FRAME);
		}
	}
	return received;
}

CSocketImpl* CWebSocketImpl::acceptConnection(CSocketAddress& clientAddr)
{
	throw InvalidAccessException("Cannot acceptConnection() on a WebSocketImpl");
}

void CWebSocketImpl::connect(const CSocketAddress& address)
{
	throw InvalidAccessException("Cannot connect() a WebSocketImpl");
}

void CWebSocketImpl::connect(const CSocketAddress& address, const CTimeSpan& timeout)
{
	throw InvalidAccessException("Cannot connect() a WebSocketImpl");
}

void CWebSocketImpl::connectNB(const CSocketAddress& address)
{
	throw InvalidAccessException("Cannot connectNB() a WebSocketImpl");
}

void CWebSocketImpl::bind(const CSocketAddress& address, bool reuseAddress)
{
	throw InvalidAccessException("Cannot bind() a WebSocketImpl");
}

void CWebSocketImpl::bind6(const CSocketAddress& address, bool reuseAddress, bool ipV6Only)
{
	throw InvalidAccessException("Cannot bind6() a WebSocketImpl");
}

void CWebSocketImpl::listen(int backlog)
{
	throw InvalidAccessException("Cannot listen() on a WebSocketImpl");
}

void CWebSocketImpl::close()
{
	m_pStreamSocketImpl->close();
	reset();
}

void CWebSocketImpl::shutdownReceive()
{
	m_pStreamSocketImpl->shutdownReceive();
}

void CWebSocketImpl::shutdownSend()
{
	m_pStreamSocketImpl->shutdownSend();
}

void CWebSocketImpl::shutdown()
{
	m_pStreamSocketImpl->shutdown();
}

int CWebSocketImpl::sendTo(const void* buffer, int length, const CSocketAddress& address, int flags)
{
	throw InvalidAccessException("Cannot sendTo() on a WebSocketImpl");
}

int CWebSocketImpl::receiveFrom(void* buffer, int length, CSocketAddress& address, int flags)
{
	throw InvalidAccessException("Cannot receiveFrom() on a WebSocketImpl");
}

void CWebSocketImpl::sendUrgent(unsigned char data)
{
	throw InvalidAccessException("Cannot sendUrgent() on a WebSocketImpl");
}

bool CWebSocketImpl::secure() const
{
	return m_pStreamSocketImpl->secure();
}

void CWebSocketImpl::setSendTimeout(const CTimeSpan& timeout)
{
	m_pStreamSocketImpl->setSendTimeout(timeout);
}

CTimeSpan CWebSocketImpl::getSendTimeout()
{
	return m_pStreamSocketImpl->getSendTimeout();
}

void CWebSocketImpl::setReceiveTimeout(const CTimeSpan& timeout)
{
	m_pStreamSocketImpl->setReceiveTimeout(timeout);
}

CTimeSpan CWebSocketImpl::getReceiveTimeout()
{
	return m_pStreamSocketImpl->getReceiveTimeout();
}


NET_NAMESPACE_END
